package com.chase.passwordmaster.search

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.AsyncTask
import android.os.Build
import android.os.Bundle
import android.view.View
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager.widget.ViewPager
import com.chase.passwordmaster.R
import com.chase.passwordmaster.config.SP_KEY_SETTING_OPTIONAL_SEARCH
import com.chase.passwordmaster.data.AccountViewModel
import com.chase.passwordmaster.detail.DetailActivity
import com.chase.passwordmaster.detail.edit.EditActivity
import com.chase.passwordmaster.entity.DecryptedAccount
import com.chase.passwordmaster.utils.*
import com.google.android.material.tabs.TabLayout
import com.mylhyl.circledialog.CircleDialog
import kotlin.collections.ArrayList

class SearchActivity : AppCompatActivity() {
    companion object {
        fun actionStart(context: Context, search: String? = null) {
            val intent = Intent(context, SearchActivity::class.java)
            search?.let { intent.putExtra("search", search) }
            context.startActivity(intent)
        }
    }

    private lateinit var accountViewModel: AccountViewModel
    private lateinit var spUtils: SPUtils


    private var searchContent: String? = null

    private lateinit var cpBack: View
    private lateinit var cpSearchContent: EditText
    private lateinit var cpSearch: View
    private lateinit var cpProgress: View

    private lateinit var cpTabLayout: TabLayout
    private lateinit var cpViewPager: ViewPager

    private val titles = listOf(
        "网站",
        "用户名",
        "手机",
        "备注",
        "邮箱",
        "QQ",
        "微信",
        "昵称"
    )

    private val searchResultList: MutableList<List<DecryptedAccount>> = arrayListOf(
        ArrayList(),
        ArrayList(),
        ArrayList(),
        ArrayList(),
        ArrayList(),
        ArrayList(),
        ArrayList(),
        ArrayList()
    )
    private val rvAdapterList: MutableList<SearchRVAdapter> = ArrayList()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_search)

        accountViewModel = ViewModelProviders.of(this).get(AccountViewModel::class.java)
        spUtils = SPUtils(this, "pmConfigs")

        cpBack = findViewById(R.id.back_search)
        cpSearchContent = findViewById(R.id.tv_search)
        cpSearch = findViewById(R.id.search_search)
        cpProgress = findViewById(R.id.progress_item_search_page)

        cpTabLayout = findViewById(R.id.tab_layout_search)
        cpViewPager = findViewById(R.id.view_pager_search)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.navigationBarColor = Color.WHITE
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                window.navigationBarDividerColor = Color.TRANSPARENT
            }
            // 设置导航栏、状态栏图标颜色为黑色
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                this.window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR
                        or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR)
            }
        }

        getInfoFromIntent()

        initSearchedAccounts()

        initCPBack()

        initCPSearch()

        createAdapters()

        initCPTabLayoutViewPager()

        initObserver()
    }

    private fun initCPBack() {
        cpBack.setOnClickListener { onBackPressed() }
    }

    private fun createAdapters() {
        searchResultList.forEach { list ->
            rvAdapterList.add(
                SearchRVAdapter(
                    list,
                    SearchRVAdapter.RInfo(
                        rvLayout = R.layout.item_search_rv,
                        tvWebsiteId = R.id.tv_website_item_search_rv,
                        tvUsernameId = R.id.tv_username_item_search_rv,
                        tvName = R.id.tv_name_item_search_rv,
                        lName = R.id.layout_name_item_search_rv,
                        tvWeChat = R.id.tv_weChat_item_search_rv,
                        tvQQ = R.id.tv_qq_item_search_rv,
                        tvEmail = R.id.tv_email_item_search_rv,
                        tvTel = R.id.tv_phone_item_search_rv,
                        lQQ = R.id.layout_qq_item_search_rv,
                        lWeChat = R.id.layout_weChat_item_search_rv,
                        lEmail = R.id.layout_email_item_search_rv,
                        lTel = R.id.layout_phone_item_search_rv,
                        blurLayout = R.id.blur_layout_item_rv,
                        blur = R.id.blur_item_rv,
                        delete = R.id.delete_item_rv,
                        edit = R.id.edit_item_rv
                    )
                ).apply {
                    itemClickListener = { holder, position ->
                        holder.itemView.setOnClickListener {
                            DetailActivity.actionStart(
                                this@SearchActivity,
                                // 这里不能使用list（）searchResultList的元素，因为在refresh的时候引用变了
                                // 下同
                                (accountList[position] as AccountViewModel.AccountIndexed).index
                            )
                        }
                    }

                    itemLongClickListener = { holder, position ->
                        holder.itemView.setOnLongClickListener {
                            // Vibrate
                            vibrate()

                            // 设置模糊遮罩
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                                holder.cpBlur.setBlurredView(holder.itemView.findViewById(R.id.body_item_search_rv))
                                holder.cpBlur.invalidate()
                            }
                            // 显示遮罩
                            showBlurCover(holder.cpBlurLayout)
                            // 点击撤回遮罩
                            holder.cpBlurLayout.setOnClickListener(::hideBlurCover)

                            // 点击遮罩中的删除弹出删除对话框
                            holder.cpDelete.setOnClickListener {
                                val index =
                                    (accountList[position] as AccountViewModel.AccountIndexed).index

                                CircleDialog.Builder()
                                    .setRadius(20)
                                    .setWidth(0.8f)
                                    .setTitle("删除账户")
                                    .setText(
                                        "\n网站：${accountViewModel.getAccount(index)?.website}\n账号：${accountViewModel.getAccount(
                                            index
                                        )?.username}\n"
                                    )
                                    .setPositive("删除") {
                                        accountViewModel.removeAccount(index)
                                    }
                                    .setNegative("取消", null)
                                    .show(supportFragmentManager)
                            }

                            // 点击遮罩中的编辑进入编辑页面
                            holder.cpEdit.setOnClickListener {
                                EditActivity.actionStart(this@SearchActivity, (accountList[position] as AccountViewModel.AccountIndexed).index)
                            }

                            // LongClick的返回值为false表示只执行长按的事件
                            // 为true表示执行完长按事件之后会执行点击事件OnClickListener
                            false
                            true
                        }
                    }
                }
            )
        }
    }

    private fun initCPTabLayoutViewPager() {
        cpViewPager.adapter = SearchPagerAdapter(
            context = this,
            searchResultList = searchResultList,
            titles = titles,
            initItem = { view: View, position: Int ->
                val rv = view.findViewById<RecyclerView>(R.id.rv_item_search_page)
                rv.layoutManager = LinearLayoutManager(this)
                rv.adapter = rvAdapterList[position]

                // The sum of search result displayed at the bottom
                val cpNumber = view.findViewById<TextView>(R.id.number_item_search_page)
                try {
                    cpNumber.text = searchResultList[position].size.toString()
                } catch (e: IndexOutOfBoundsException) {
                    cpNumber.text = "0"
                    e.printStackTrace()
                }

                val cpEmpty = view.findViewById<View>(R.id.empty_item_search_page)
                try {
                    if (searchResultList[position].isNotEmpty()) {
                        rv.visibility = View.VISIBLE
                        cpEmpty.visibility = View.GONE
                    } else {
                        rv.visibility = View.GONE
                        cpEmpty.visibility = View.VISIBLE
                    }
                } catch (e: IndexOutOfBoundsException) {
                    rv.visibility = View.GONE
                    cpEmpty.visibility = View.VISIBLE
                    e.printStackTrace()
                }
            }
        )

        cpTabLayout.setupWithViewPager(cpViewPager, false)
    }

    private fun initObserver() {
        accountViewModel.getAccountLiveData().observe(this, Observer {
            searchContent?.let {
                SearchTask().execute(it)
            }
        })
    }

    private fun initCPSearch() {
        //收起软键盘
        fun closeKeyboard() {
            val im = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            this.currentFocus?.let {
                im.hideSoftInputFromWindow(
                    it.windowToken, InputMethodManager.HIDE_NOT_ALWAYS
                )
            }
        }

        // 执行搜索
        fun search() {
            val content = cpSearchContent.text.toString()
            if (content.isNotBlank()) {
                searchContent = content
            }

            searchContent?.let {
                cpProgress.visibility = View.VISIBLE
                SearchTask().execute(it)
            }
        }

        cpSearchContent.setOnEditorActionListener { v, actionId, event ->
            if (EditorInfo.IME_ACTION_GO == actionId) {
                search()
                closeKeyboard()

                return@setOnEditorActionListener true
            }
            false
        }

        cpSearch.setOnClickListener {
            search()
            closeKeyboard()
        }
    }

    private fun getInfoFromIntent() {
        searchContent = intent.getStringExtra("search")
    }

    private fun initSearchedAccounts() {
        searchContent?.let {
            SearchTask().execute(it)
        }
    }

    inner class SearchTask : AsyncTask<String, Int, MutableList<List<DecryptedAccount>>>() {
        override fun doInBackground(vararg params: String?): MutableList<List<DecryptedAccount>> {
            params[0]?.let {
                if (spUtils.getBoolean(SP_KEY_SETTING_OPTIONAL_SEARCH, false)) {
                    for (i in 0 until searchResultList.size) {
                        searchResultList[i] = emptyList()
                    }
                    when (cpViewPager.currentItem) {
                        0 -> searchResultList[0] = accountViewModel.findAccountByWebsite(it)
                        1 -> searchResultList[1] = accountViewModel.findAccountByUsername(it)
                        2 -> searchResultList[2] = accountViewModel.findAccountByTel(it)
                        3 -> searchResultList[3] = accountViewModel.findAccountByMemo(it)
                        4 -> searchResultList[4] = accountViewModel.findAccountByEmail(it)
                        5 -> searchResultList[5] = accountViewModel.findAccountByQQ(it)
                        6 -> searchResultList[6] = accountViewModel.findAccountByWeChat(it)
                        7 -> searchResultList[7] = accountViewModel.findAccountByName(it)
                    }
                } else {
                    searchResultList[0] = accountViewModel.findAccountByWebsite(it)
                    searchResultList[1] = accountViewModel.findAccountByUsername(it)
                    searchResultList[2] = accountViewModel.findAccountByTel(it)
                    searchResultList[3] = accountViewModel.findAccountByMemo(it)
                    searchResultList[4] = accountViewModel.findAccountByEmail(it)
                    searchResultList[5] = accountViewModel.findAccountByQQ(it)
                    searchResultList[6] = accountViewModel.findAccountByWeChat(it)
                    searchResultList[7] = accountViewModel.findAccountByName(it)
                }
            }
            return searchResultList
        }

        override fun onPostExecute(result: MutableList<List<DecryptedAccount>>?) {
            cpProgress.visibility = View.GONE
            result?.let {
                rvAdapterList.forEachIndexed { index, searchRVAdapter ->
                    searchRVAdapter.accountList = it[index]
                }
                rvAdapterList.forEach { it.notifyDataSetChanged() }
                cpViewPager.adapter?.notifyDataSetChanged()
            }
        }
    }

    // 显示模糊遮罩
    private fun showBlurCover(blurCover: View) {
        blurCover.visibility = View.VISIBLE
        blurCover.alpha = 1f
        val animation = AnimationUtils.loadAnimation(this, R.anim.alpha_show)
        blurCover.startAnimation(animation)
    }

    // 隐藏模糊遮罩
    private fun hideBlurCover(blurCover: View) {
        val animation = AnimationUtils.loadAnimation(this, R.anim.alpha_hide)
            .apply {
                setAnimationListener(object: Animation.AnimationListener {
                    override fun onAnimationRepeat(animation: Animation?) { }

                    override fun onAnimationStart(animation: Animation?) { }

                    override fun onAnimationEnd(animation: Animation?) {
                        blurCover.visibility = View.GONE
                    }

                })
            }
        blurCover.startAnimation(animation)
    }
}
